﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model.WXshopBuiness;
using Services.WXshopBuiness;
using Services.Util;
using Model.Util;
using Xproject.Util;
using System.IO;
using Services.WXProjectAdmin;
using Model.Admin;
using Model.WXshopBuiness.Enum;
using Model.WeiXin.DTO;
using Core.WeiXin;
using System.Web.Script.Serialization;

namespace WeiXinProject.Controllers
{
    public class PromotionsController : WXBaseController
    {
        WXProductServices m_WXProductServices;
        PromotionServices m_PromotionServices;
        WXOrderServices m_WXOrderServices;
      
        public PromotionsController(WXProductServices mWXProductServices,PromotionServices mPromotionServices, WXOrderServices mWXOrderServices )
        {
            m_WXProductServices = mWXProductServices;
            m_PromotionServices= mPromotionServices;
            m_WXOrderServices = mWXOrderServices;
        }

        // GET: Promotions
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 砍价促销活动
        /// </summary>
        /// <returns></returns>
        public ActionResult KJPromotions(string KanJiaID)
        {
            ViewBag.IsFoucs = this.CurrentUser.IsFocus == 1 ? true : false;
            ViewBag.zxUserId = CurrentUser.ZX_UserID;
            UserProductKanJia kjInfo = m_PromotionServices.GetUserProductKJbyID(KanJiaID);
            if (kjInfo == null)
            {
                return Redirect("/CommonBase/WarningNotice?Notice=" + "对不起，您浏览的活动不存在！");
            }
            if (kjInfo.DeadLineTime <=DateTime.Now )
            {
                return Redirect("/CommonBase/WarningNotice?Notice=" + "对不起，此活动已过期！");
            }
                      
            string  wxJsApiParam =WeiXinHelper.GetWxConfig();
            ViewBag.wxJsApiParam = wxJsApiParam;
           

            if (kjInfo != null)
            {
                //获取产品信息
                WXProduct product = m_WXProductServices.GetById(kjInfo.ProductID);
                if (product.State == 1)
                {
                    return Redirect("/CommonBase/WarningNotice?Notice=" + "对不起，您此宝贝已下架！");
                }
                if (product.State == 2)
                {
                    return Redirect("/CommonBase/WarningNotice?Notice=" + "对不起，此宝贝已不是最新的啦。到首页转转吧");
                }
                List<ProductContents> contents = new List<ProductContents>();
                List <PromotionsKanJiaDetail> alreadKanJiaInfos  = m_PromotionServices.GetKJdetailList(kjInfo.KanJiaID);
                List<string> Images = new List<string>();
                string userId = this.CurrentUser.UserID;
                if (product != null)
                {
                    if (!string.IsNullOrEmpty(product.ImageUrl1)) { Images.Add(product.ImageUrl1); }
                    if (!string.IsNullOrEmpty(product.ImageUrl2)) { Images.Add(product.ImageUrl2); }
                    if (!string.IsNullOrEmpty(product.ImageUrl3)) { Images.Add(product.ImageUrl3); }
                    if (!string.IsNullOrEmpty(product.ImageUrl4)) { Images.Add(product.ImageUrl4); }
                    if (!string.IsNullOrEmpty(product.ImageUrl5)) { Images.Add(product.ImageUrl5); }
                    if (!string.IsNullOrEmpty(product.ImageUrl6)) { Images.Add(product.ImageUrl6); }
                    if (!string.IsNullOrEmpty(product.ImageUrl7)) { Images.Add(product.ImageUrl7); }
                    if (!string.IsNullOrEmpty(product.ImageUrl8)) { Images.Add(product.ImageUrl8); }
                    if (!string.IsNullOrEmpty(product.ImageUrl9)) { Images.Add(product.ImageUrl9); }
                }

                contents = m_WXProductServices.GetProductContent(kjInfo.ProductID);

                var usermodel = Cache_UserInfoModel.GetUserInfoModel(userId);
                ViewData["ScrollImages"] = Images;
                ViewData["contents"] = contents;
                ViewData["kjInfo"] = kjInfo;
                ViewData["alreadKanJiaInfos"] = alreadKanJiaInfos;
                return View(product);
            }
            else
            {
                return View("~/CommonBase/SystemNotice");
            }
            
        }
        [HttpPost]
        /// <summary>
        /// 从购物车对商品增加砍价活动
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public JsonResult addKanJiaFromShopCar(string orderId)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
                   
                string userId = this.CurrentUser.UserID;
                WeiXinOrder order = m_WXOrderServices.GetDBOrderById(orderId); //先拿到订单信息
                WXProduct xProduct = m_WXProductServices.GetById(order.ProductId);                
                Promotions p = m_PromotionServices.GetPromotionsById(xProduct.PromotionId);
                string message = string.Empty;
                string kanjiaid = string.Empty;
                if (string.IsNullOrEmpty(p.PromotionID) || string.IsNullOrEmpty(xProduct.ProductID) || string.IsNullOrEmpty(CurrentUser.UserID))
                {
                    success = false;
                    result = "参数有误，联系管理看看~";
                    jsonData = new { Success = success, Data = result };
                    LogHelper.WriteInfoLog(" 检验是否已发起过砍价活动 参数错误 有空的参数 promotionid is :" + p.PromotionID + " productid is " + xProduct.ProductID + " userid is " + CurrentUser.UserID);
                    return Json(jsonData, JsonRequestBehavior.AllowGet);
                }
                if (m_PromotionServices.CheckUserHasCreatedThisProductKanJia(p.PromotionID, xProduct.ProductID, CurrentUser.UserID, orderId) != null)
                {
                    success = false;
                    result = "亲，您已经对此宝贝发起过砍价，赶紧去您的购物车里看看砍价情况咋样吧~,您支付完毕后才可重新发起此商品的新的砍价活动";
                    jsonData = new { Success = success, Data = result };
                    return Json(jsonData, JsonRequestBehavior.AllowGet);
                }
                int res = m_PromotionServices.AddProductKanJiaFromShopCar(order, p, xProduct, userId, CurrentUser.NickName, "直接以 砍价方式加入购物车", "<--亲，点这儿返回，更多的实惠等你发现！", 0, 0, 0, 0, 1, out message, out kanjiaid);
                if (res == 1)
                {
                    success = true;
                    result = "宝贝已加入购物车，您的砍价邀请活动专属页面即将呈现，快去分享给小伙伴们来给砍价！";
                    jsonData = new { Success = success, Data = result, KanJiaId = kanjiaid };
                }
                else
                {
                    success = false;
                    result = message;
                    jsonData = new { Success = success, Data = result };
                }

                return Json(jsonData, JsonRequestBehavior.AllowGet);        

        }
        [HttpPost]
        public JsonResult AddProductKanJia(string productId)
        {
            //生成一个购物车订单，
            string orderId = Guid.NewGuid().ToString().Replace("-","");
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            string userId = this.CurrentUser.UserID;
            WXProduct xProduct = m_WXProductServices.GetById(productId);
            string OrderName = string.Empty;
            if (xProduct == null)
            {
                jsonData = new { Success = false, Data = "产品不存在" };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }
            else
            {
                //to do 
                //检查是不是还有效，比如有些特价产品这样的，限时购的
                OrderName = xProduct.ProductName + xProduct.Spec1 + xProduct.Spec2 + xProduct.Spec3 + xProduct.Spec4 + xProduct.Spec5;
            }            
           Promotions p =   m_PromotionServices.GetPromotionsById(xProduct.PromotionId);
            string message = string.Empty;
            string kanjiaid = string.Empty;
            //生成一个 用户 --产品--砍价 活动数据
            //用户只能对产品发起一次 砍价，用完了可以再次砍
            //检测是否已经存在了此用户发起的针对此产品的还没有使用的砍价优惠活动
           
            if (string.IsNullOrEmpty(p.PromotionID)|| string.IsNullOrEmpty(xProduct.ProductID)||string.IsNullOrEmpty(CurrentUser.UserID))
            {  
                success = false;
                result = "参数有误，联系管理看看~";
                jsonData = new { Success = success, Data = result };
                LogHelper.WriteInfoLog(" 检验是否已发起过砍价活动 参数错误 有空的参数 promotionid is :"  +p.PromotionID +" productid is "+xProduct.ProductID +" userid is "+CurrentUser.UserID);
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }
            if (m_PromotionServices.CheckUserHasCreatedThisProductKanJia(p.PromotionID, xProduct.ProductID, CurrentUser.UserID, orderId) !=null)
            {
                success = false;
                result = "亲，您已经对此宝贝发起过砍价，赶紧去您的待支付订单里看看砍价情况吧~,您支付完毕后才可重新发起此商品的新的砍价活动";
                jsonData = new { Success = success, Data = result };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            } 
            int res =m_PromotionServices.AddProductKanJia(orderId,p, xProduct, OrderName, userId, CurrentUser.NickName, "直接以 砍价方式加入订单", "亲，这儿能砍价，快来帮我砍砍价", 0, 0, 0, 0,1,out message,out kanjiaid); 
            if (res == 1)
            {
                success = true;
                result = "宝贝在我的待支付订单中等您，您的砍价邀请活动专属页面即将呈现，快去分享给小伙伴们来给砍价！";
                jsonData = new { Success = success, Data = result,KanJiaId=kanjiaid };
            }
            else {
                success = false;
                result = message;
                jsonData = new { Success = success, Data = result };
            }                     
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult DoKanJia()
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;

            string KanJiaID = Request["KanJiaID"];
            if (string.IsNullOrEmpty(KanJiaID))
            {
                jsonData = new { Success = false, Data = "没有砍价ID" };            
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }
            UserProductKanJia kjInfo = m_PromotionServices.GetUserProductKJbyID(KanJiaID);
            if (kjInfo == null)
            {
                jsonData = new { Success = false, Data = "砍价活动不存在" };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }
            if(kjInfo.DeadLineTime<=DateTime.Now)
            {
                jsonData = new { Success = false, Data = "下回要快点哦，朋友等的花儿都谢了" };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }
            if (kjInfo.AlreadKanJiaCount >= kjInfo.MaxKanJiaCount)
            {
                jsonData = new { Success = false, Data = "朋友人气爆棚，已收集满能量，谢谢哦" };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }
            if (kjInfo.AleradKanJiaMoney >= kjInfo.MaxKanJiaMoney)
            {
                jsonData = new { Success = false, Data = "朋友运气爆棚，不能再砍了，再砍我们血本都没了，谢谢哦" };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }
            string   message = string.Empty;
            decimal kanjianmoney = 0.00M;
            int res =m_PromotionServices.DoAnKanJia(kjInfo, this.CurrentUser.UserID, this.CurrentUser.NickName,out kanjianmoney, out message);

            if (res != 1)
            {
                success = false;
                result = message;
            }
            else
            {
                success = true;
                result =   kanjianmoney.ToString("#0.00") ;
            }
           
            jsonData = new { Success = success, Data = result };

            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
    }
}